<?php
declare(strict_types=1);

namespace support;

use Illuminate\Database\Events\QueryExecuted;
class SqlRecord
{
    public static array   $sql      = [];

    public static function start($worker)
    {
        DB::connection()->listen(function (QueryExecuted $query) {
            $bindings = $query->bindings;
            $sql = $query->sql;
            foreach ($bindings as $replace) {
                $value = is_numeric($replace) ? (string)$replace : "'" . $replace . "'";
                $sql = preg_replace('/\?/', $value, $sql, 1);
            }
            $sql = sprintf('[%s ms] %s', $query->time, $sql);
            self::$sql[] = $sql;
            write_log(msg: '', extend: $sql, level: 'info',channel: 'sql');
        });
    }

    public static function getSqls(): array
    {
        $env = config('app.env');
        if (!in_array($env, ['local', 'testing'])) {
            return [];
        }
        return self::$sql;
    }
}
